package com.librait.mapstracker;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.kristijandraca.backgroundmaillibrary.BackgroundMail;


public class MainActivity extends ActionBarActivity {
	
	private GoogleMap map;
	
	private double CURRENT_KM = 0.0;
	private String CURRENT_TARGET = "";
	private String CURRENT_TARGET_LOCATION = "6505 Mississauga RD, Mississauga, Ontario";
	private String LAST_TRACKING_TIME = "";
	private String CURRENT_STATUS = "";
	private boolean CURRENT_NAVIGATION = false;
	
	Button start_tracking_button;
	Button pause_tracking_button;
	Button stop_tracking_button;
	
	Spinner clientsSpinner;
	
	TextView kmTextView;
	TextView kmCurrentTextView;
	TextView timeDrivingTextView;
	
	Chronometer timeDrivingChronometer;
	
	LatLng libraIT;
		
	boolean firstOpen = true;

	String userName;
	String userPass;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
		
		LatLng libraIT = new LatLng(43.598008, -79.736216);
		
		map.setMyLocationEnabled(true);
		map.moveCamera(CameraUpdateFactory.newLatLngZoom(libraIT, 16));
		map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
		
		clientsSpinner = (Spinner) findViewById(R.id.clientsSpinner);
		
		addItemSelectedListenerToSpinner();
		
		start_tracking_button = (Button) findViewById(R.id.start_tracking_button);
		pause_tracking_button = (Button) findViewById(R.id.pause_tracking_button);
		stop_tracking_button = (Button) findViewById(R.id.stop_tracking_button);
		
		setButtonOnClickListeners();
		
		kmTextView = (TextView) findViewById(R.id.kmTextView);
		kmCurrentTextView = (TextView) findViewById(R.id.kmCurrentTextView);
		timeDrivingTextView = (TextView) findViewById(R.id.timeDrivingTextView);
		
		timeDrivingChronometer = (Chronometer) findViewById(R.id.timeDrivingChronometer);
		
		userName = RegisterActivity.getSavedString("email");
		userPass = RegisterActivity.getSavedString("password");
		
	}

	private void addItemSelectedListenerToSpinner(){
    	clientsSpinner.setOnItemSelectedListener(new OnItemSelectedListener(){

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Pull address from clients SQL information
				// If multiple addresses, pop dialog box to confirm which one
				CURRENT_TARGET = clientsSpinner.getSelectedItem().toString();
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
    		
    	});
    }
	private void setButtonOnClickListeners(){
	    	start_tracking_button.setOnClickListener(new OnClickListener(){

	    		// TODO start navigation to currently selected spinner item.
	    		//Navigate to CURRENT_TARGET_LOCATION
	    		// Error check for no information in spinner
	    		// Start KM tracking
				@Override
				public void onClick(View arg0){
					if(CURRENT_NAVIGATION == false){
						int stoppedMilliseconds = 0;
					CURRENT_STATUS = getString(R.string.leaving_for_email_subject) + " " + CURRENT_TARGET;
					CURRENT_NAVIGATION = true;
					
					String chronoText = timeDrivingChronometer.getText().toString();
					String array[] = chronoText.split(":");
					
					if(array.length==2){
						stoppedMilliseconds = Integer.parseInt(array[0]) * 60 * 1000+ Integer.parseInt(array[1]) *1000;
						
					} else if(array.length == 3){
						stoppedMilliseconds = Integer.parseInt(array[0]) * 60 * 60 *1000+ Integer.parseInt(array[1]) * 60*1000
								+ Integer.parseInt(array[2])*1000;
					}
					timeDrivingChronometer.setBase(SystemClock.elapsedRealtime() - stoppedMilliseconds);

					BackgroundMail bm = new BackgroundMail(MainActivity.this);
					bm.setGmailUserName(userName);
					bm.setGmailPassword(userPass);
					bm.setMailTo("danielzaccagnini@gmail.com");
					bm.setFormSubject(CURRENT_STATUS);
					bm.setFormBody("");
					bm.send();
					timeDrivingChronometer.start();
				} 
				}
	    		
	    	});
	    	pause_tracking_button.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View v) {
					timeDrivingChronometer.stop();
				}
	    		
	    	});
	    	
	    	stop_tracking_button.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View v) {
					// Need to update Commit expense with tracking time and km
					
					if(CURRENT_NAVIGATION == true){
						createDialog();
					} else {
						createPopUp();
					}
				}
				
				private void createPopUp() {
					AlertDialog.Builder noNaviPopUp = new AlertDialog.Builder(MainActivity.this);
					noNaviPopUp.setMessage("You did not start navigating");
					noNaviPopUp.setCancelable(true);
					noNaviPopUp.setPositiveButton("Okay", new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							
						}
					});
				}

				private void createDialog() {

					AlertDialog.Builder confirmStop = new AlertDialog.Builder(MainActivity.this);
					confirmStop.setMessage("Confirm that you are finished");
					confirmStop.setCancelable(true);
					
					confirmStop.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface arg0, int arg1) {
							// TODO Auto-generated method stub
							LAST_TRACKING_TIME = timeDrivingChronometer.getText().toString();
							CURRENT_NAVIGATION = false;
							CURRENT_STATUS = getString(R.string.arriving_at_email_subject) + " " + CURRENT_TARGET;
							timeDrivingChronometer.stop();
							
							BackgroundMail bm = new BackgroundMail(MainActivity.this);
							bm.setGmailUserName(userName);
							bm.setGmailPassword(userPass);
							bm.setMailTo("danielzaccagnini@gmail.com");
							bm.setFormSubject(CURRENT_STATUS);
							bm.setFormBody("");
							bm.send();
							
							timeDrivingChronometer.setBase(SystemClock.elapsedRealtime());						}
						
					});
					
					confirmStop.setNegativeButton("No",
		                    new DialogInterface.OnClickListener() {
		                public void onClick(DialogInterface dialog, int id) {
		                    dialog.cancel();
		                }
		            });
					AlertDialog popUpConfirm = confirmStop.create();
					popUpConfirm.show();
				}
	    		
	    	});
	    }
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();

		if (id == R.id.user_credentials) {
			Intent intent = new Intent(MainActivity.this, RegisterActivity.class);
			startActivity(intent);
		}
		return super.onOptionsItemSelected(item);
	}

}
